<?php

class Controller_A2demo extends Controller {

	private $_name;

    public function before()
	{
	    $this->a2 = A2::instance('a2-demo');
		$this->a1 = $this->a2->a1;
		$this->_name = $this->request->controller();

		$this->user = $this->a2->get_user();

		echo 'This demo uses KO3. For demo using Kohana 2.3.4 go <a href="http://www.nanodocumet.com/kohana/authdemo/">here</a>';
		echo '<div style="position:absolute;top:0px;right:10px;background-color:#f0f0f0;font-weight:bold;padding:5px;">',
             html::anchor($this->_name.'/','index'),'-',
		     html::anchor($this->request->uri().'?profiler=true','Show profiler'),'-',
		     html::anchor($this->_name.'/db','DB'),'</div>';
	}

	public function after()
	{
	    // Showing the profiler if using debug mode
	    if (!empty($_GET['profiler']))
	        echo View::factory('profiler/stats');
	}

	public function action_index()
	{
        $blogs = ORM::factory('blog')->find_all();

        // show user info
        echo $this->user_info();

        // show blogs
        echo '<hr />';

        if(count($blogs) === 0)
        {
            echo 'No blogs yet<br />';
        }
        else
        {
            foreach($blogs as $blog)
            {
                echo $blog->text . ' by <strong><i>' . $blog->user->username . '</i></strong><br />';
                $e = "";
                $d = "";
                if ($this->user) {
                    $e = ($this->a2->allowed($blog,'edit'))? html::anchor($this->_name.'/edit/'.$blog->id,'Edit') : "";
                    $d = ($this->a2->allowed($blog,'delete'))? ' - '.html::anchor($this->_name.'/delete/'.$blog->id,'Delete') : "";
                }
                echo $e,$d,'<hr />';
            }
        }
        if ($this->user){
          echo html::anchor($this->_name.'/add','Add');
        }
	}

	private function user_info()
	{
        $s = "Use admin:admin (username:password) for Admin role. Use author:author (username:password) for Author role <br />";
        if( $this->user )
        {
            $s .=  '<b><i>'.$this->user->username.' </i></b> ' . html::anchor($this->_name.'/logout','Logout');
        }
        else
        {
            $s .= '<b>Guest</b> ' . html::anchor($this->_name.'/login','Login') . ' - ' . html::anchor($this->_name.'/create','Create account');
        }

		return '<div style="width:95%;padding:5px;background-color:#AFB6FF;">' . $s . '</div>';
	}

	public function action_create()
	{
	    if($this->user) //cannot create new accounts when a user is logged in
		{
			$this->action_index();
		}
        if (!empty($_POST))
        {
			$post = $_POST;

			// Create a new user
			$user = ORM::factory('user')
				->values($post);

			if ($user->check())
			{
			    // Saving login role and the one coming from dropdown menu
        	    $user->save();
       		    $user->add('roles', ORM::factory('role', array('name' => 'login')));
        	    $user->add('roles', ORM::factory('role', array('id' => $post['role'])));

				// user  created, show login form
				$this->action_login();
			}
		    echo Debug::vars($user->validation()->errors());
		}
		else
		{
		    //show form
            echo form::open();
            echo 'username:' . form::input('username') . '<br />';
            echo 'password:' . form::password('password') . '<br />';
            echo 'password confirm:' . form::password('password_confirm') . '<br />';
            echo 'email:' . form::input('email') . '<br />';
            echo 'role:' . form::select('role',array('3'=>'author','2'=>'admin')) . '<br />';
            echo form::submit('create','create');
            echo form::close();




		}
	}

	public function action_login()
	{
		if($this->user) //cannot create new accounts when a user is logged in
		{
			return $this->action_index();
		}

		$post = Validation::factory($_POST)
			->rule('username', 'not_empty')
			->rule('username', 'min_length', array(':value', 4))
			->rule('username', 'max_length', array(':value', 32))
			->rule('password', 'not_empty')
			->rule('password', 'min_length', array(':value', 6))
			->rule('password', 'max_length', array(':value', 32));

		if($post->check())
		{
			echo '<br />checked';
			if($this->a1->login($post['username'],$post['password'], isset($_POST['remember']) ? (bool) $_POST['remember'] : FALSE))
			{
				$this->request->redirect($this->_name.'/index' );
			}
		}

		//show form
		echo form::open();
		echo 'username:' . form::input('username') . '<br>';
		echo 'password:' . form::password('password') . '<br>';
		echo 'remember me:' . form::checkbox('remember',TRUE) . '<br>';
		echo form::submit('login','login');
		echo form::close();
		echo Debug::vars($post->errors());

	}

	public function action_logout()
	{
		$this->a1->logout();
		$this->user = NULL;
		return $this->action_index();
	}

	public function action_add()
	{
		if(!$this->a2->allowed('blog','add'))
		{
			echo '<b>You are not allowed to add blogs</b><br>';
			return $this->action_index();
		}

		$blog = ORM::factory('blog');

		$this->editor($blog);
	}

	public function action_edit($blog_id)
	{
		$blog = ORM::factory('blog',$blog_id);

		// NOTE the use of the actual blog object in the allowed method call!
		if(!$this->a2->allowed($blog,'edit'))
		{
			echo '<b>You are not allowed to edit this blog</b><br>';
			return $this->action_index();
		}

		$this->editor($blog);
	}

	private function editor($blog)
	{
		if(count($_POST))
		{
			$blog->values($_POST);

			if($blog->check())
			{
				// Check if user_id is not empty, that means an admin is editing
				$blog->user_id = (empty($blog->user_id))? $this->a2->get_user()->id : $blog->user_id;
				$blog->save();
				return $this->action_index();
			}
		}

		//show form
		echo form::open();
		echo 'text:' . form::textarea('text',$blog->text) . '<br>';
		echo form::submit('post','post');
		echo form::close();
		echo Kohana::debug($blog->validate()->errors());

	}

	public function action_delete($blog_id)
	{
		$blog = ORM::factory('blog',$blog_id);

		// NOTE the use of the actual blog object in the allowed method call!
		if(!$this->a2->allowed($blog,'delete'))
		{
			echo '<b>You are not allowed to delete this blog</b><br>';
		}
		else
		{
			$blog->delete();
		}

		$this->action_index();
	}

	public function action_db()
	{
		echo '<b>Mysql DB structure</b><hr>';

		echo "<pre>
        CREATE TABLE IF NOT EXISTS `roles` (
          `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
          `name` varchar(32) NOT NULL,
          `description` varchar(255) NOT NULL,
          PRIMARY KEY  (`id`),
          UNIQUE KEY `uniq_name` (`name`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        INSERT INTO `roles` (`id`, `name`, `description`) VALUES(1, 'login', 'Login privileges, granted after account confirmation');
        INSERT INTO `roles` (`id`, `name`, `description`) VALUES(2, 'admin', 'Administrative user, has access to everything.');
        INSERT INTO `roles` (`id`, `name`, `description`) VALUES(3, 'author', 'Can create posts. Delete and edit own posts.');

        CREATE TABLE IF NOT EXISTS `roles_users` (
          `user_id` int(10) UNSIGNED NOT NULL,
          `role_id` int(10) UNSIGNED NOT NULL,
          PRIMARY KEY  (`user_id`,`role_id`),
          KEY `fk_role_id` (`role_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

        CREATE TABLE IF NOT EXISTS `users` (
          `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
          `email` varchar(127) NOT NULL,
          `username` varchar(32) NOT NULL DEFAULT '',
          `password` char(50) NOT NULL,
          `logins` int(10) UNSIGNED NOT NULL DEFAULT '0',
          `last_login` int(10) UNSIGNED,
          PRIMARY KEY  (`id`),
          UNIQUE KEY `uniq_username` (`username`),
          UNIQUE KEY `uniq_email` (`email`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        CREATE TABLE IF NOT EXISTS `user_tokens` (
          `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
          `user_id` int(11) UNSIGNED NOT NULL,
          `user_agent` varchar(40) NOT NULL,
          `token` varchar(32) NOT NULL,
          `created` int(10) UNSIGNED NOT NULL,
          `expires` int(10) UNSIGNED NOT NULL,
          PRIMARY KEY  (`id`),
          UNIQUE KEY `uniq_token` (`token`),
          KEY `fk_user_id` (`user_id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        ALTER TABLE `roles_users`
          ADD CONSTRAINT `roles_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
          ADD CONSTRAINT `roles_users_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;

        ALTER TABLE `user_tokens`
          ADD CONSTRAINT `user_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

        CREATE TABLE IF NOT EXISTS `blogs` (
          `id` int(12) unsigned NOT NULL auto_increment,
          `user_id` int(12) unsigned NOT NULL,
          `text` text NOT NULL,
          PRIMARY KEY  (`id`),
          KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        ALTER TABLE `blogs`
          ADD CONSTRAINT `blogs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
		</pre>";
	}

}